<?php

namespace app\admin\controller;

use app\models\{Agent as Agents, Region, AgentLog, Subcate, Cate, Product, Withdraw, Promo, Order, Douyin, Pkey, Coupon};
use think\Db;
use think\Validate;
use EasyWeChat\Factory;


class Agent extends Base
{

    public function index_exc()
    {
        if ($this->request->isAjax()) {
            $data = input();
            $validate = new Validate([
                'id' => 'require',
            ], [
                'id.require' => 'ID不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            //查询代理是否已存在
            $agent = (new Agents())->where(['id' => $data['id'], 'status' => 1])->find();
            if (empty($agent)) {
                return json(['code' => 1, 'msg' =>  '代理不存在或已冻结']);
            }
            $cates = (new Cate())->where('isshow', 1)->order('sort desc')->select();
            //根据分类导入
            $text = '';
            try {
                foreach ($cates as $cate) {
                    //查找子分类
                    $subcates = (new Subcate())->where(['isshow' => 1, 'cate' => $cate['id'], 'agentid' => 0])->order('sort desc')->select();
                    foreach ($subcates as $subcate) {
                        /************1、判断子分类是否需要导入*************/
                        $sub = (new Subcate())->whereOr(function ($query) use ($subcate, $data) {
                            $query->where(['isshow' => 1, 'topid' => $subcate['id'], 'agentid' => $data['id']]);
                        })->whereOr(function ($query) use ($subcate, $data) {
                            $query->where(['isshow' => 1, 'name' => $subcate['name'], 'agentid' => $data['id']]);
                        })->find();
                        //先导入子分类获取已导入的分类ID
                        if (empty($sub)) {
                            $agentsub = [
                                'agentid' => $data['id'],
                                'cate' => $subcate['cate'],
                                'name' => $subcate['name'],
                                'isshow' => $subcate['isshow'],
                                'images' => $subcate['images'],
                                'sort' => $subcate['sort'],
                                'topid' => $subcate['id'],
                            ];
                            $subcateid = (new Subcate())->insertGetId($agentsub);
                            if (!$subcateid) {
                                $text = $text . '子分类[' . $subcate['name'] . ']导入失败<br/>';
                                continue;
                            }
                        } else {
                            $subcateid = $sub['id'];
                        }
                        //查找子分类下系统产品
                        $products = (new Product())->where(['subcate' => $subcate['id'], 'agentid' => 0, 'isdel' => 1, 'isshow' => 1])->select();
                        /************1、判断产品是否需要导入*************/
                        foreach ($products as $product) {
                            $sproduct = (new Product())
                                ->whereOr(function ($query) use ($product, $data) {
                                    $query->where(['isshow' => 1, 'topid' => $product['id'], 'agentid' => $data['id'], 'isdel' => 1]);
                                })->whereOr(function ($query) use ($product, $data) {
                                    $query->where(['isshow' => 1, 'title' => $product['title'], 'agentid' => $data['id'], 'isdel' => 1]);
                                })->find();
                            //不存在就导入产品
                            if (empty($sproduct)) {
                                $drpro = [
                                    'agentid' => $data['id'],
                                    'cate' => $subcate['cate'],
                                    'type' =>  $product['type'],
                                    'subcate' => $subcateid,
                                    'price' => $product['price'],
                                    'title' => $product['title'],
                                    'descs' => $product['descs'],
                                    'images' => $product['images'],
                                    'ishot' => $product['ishot'],
                                    'isshow' => $product['isshow'],
                                    'sort' => $product['sort'],
                                    'topid' => $product['id'],
                                ];
                                $res = (new Product())->allowfield(true)->save($drpro);
                                if (!$res) {
                                    $text = $text . '产品[' . $product['title'] . ']导入失败<br/>';
                                    continue;
                                }
                            }
                        }
                    }
                }
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'msg' => '操作成功']);
        }
    }

    public function withdraw()
    {
        if ($this->request->isAjax()) {
            $model = new Withdraw();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['name|cards', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['agentid'])) {
                $where[] = ['user_id', 'in', $post['agentid']];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['agent_name'] = (new Agents())->where(['id' => $lists['user_id']])->value('nickname') ?? '';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }

    public function withdraw_status()
    {
        $id = input('id');
        $status = input('status/s', '0');
        $text = input('text');
        if (!empty($id)) {
            if ($status != 2 && $status != 3) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据状态错误']);
            }
            $model = new Withdraw();
            $cate = $model->where(['id' => $id])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            if ($cate['status'] != 1) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据已审核，无需重复审核']);
            }
            if ($status == 3 && empty($text)) {
                return json(['code' => 1, 'data' => [], 'msg' => '请填写驳回理由']);
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update(['status' => $status, 'text' => $text]);
                if ($status == 3) {
                    (new Agents())->MoneyEdit($cate['user_id'], 3, $cate['money'], '提现驳回', $cate['id']);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function product()
    {
        if ($this->request->isAjax()) {
            $model = new Product();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['isdel', '=', 1];
            $where[] = ['agentid', '>', 0];
            if (!empty($post['title'])) {
                $where[] = ['title', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['agentid'])) {
                $where[] = ['agentid', '=', $post['agentid']];
            }
            if (!empty($post['cate'])) {
                $where[] = ['cate', '=', $post['cate']];
            }
            if (!empty($post['isshow'])) {
                $where[] = ['isshow', '=', $post['isshow']];
            }
            if (!empty($post['ishot'])) {
                $where[] = ['ishot', '=', $post['ishot']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["sort" => "desc", "id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['agent_name'] = '系统';
                if ($lists['agentid'] > 0) {
                    $lists['agent_name'] = (new Agents())->where(['id' => $lists['agentid']])->value('nickname') ?? '';
                }
                $lists['cate_name'] = (new Cate())->where(['id' => $lists['cate']])->value('name') ?? '无';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'cate' => (new Cate())->field('id,name,isshow')->order(['sort' => 'desc'])->select(),
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }


    public function product_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'agentid' => 'require',
                'cate' => 'require'
            ], [
                'title.require' => '标题不能为空',
                'agentid.require' => '代理不能为空',
                'cate.require' => '分类不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if (!empty($data['id'])) {
                $res = (new Product())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new Product())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Product())->where('id', $id)->find();
            $subcate = [];
            if (empty($row)) {
                $agentid = $this->request->get('agentid/d', 0);
                $row['agentid'] = $agentid;
            } else {
                $where[] = ['cate', '=', $row['cate']];
                $where[] = ['agentid', '=', $row['agentid']];
            }
            return view('', [
                'row' => $row,
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select(),
                'cate' => (new Cate())->field('id,name,isshow')->order('sort desc')->select()
            ]);
        }
    }

    public function product_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new Product();
            $cate = $model->where(['id' => $id])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'isshow':
                    $status = $cate['isshow'] == 1 ? 2 : 1;
                    break;
                case 'ishot':
                    $status = $cate['ishot'] == 1 ? 2 : 1;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function product_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Product();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update(['isdel' => 2]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    } 

    public function agentlog()
    {
        if ($this->request->isAjax()) {
            $model = new AgentLog();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $agentid = input('agentid/d') ?? 0;
            $where = array();
            $where[] = ['user_id', '=', $agentid];
            if (!empty($post['types'])) {
                $where[] = ['types', '=', $post['types']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $row) {
                if ($row['source'] > 0 && $row['type'] == 1) {
                    $order = (new Order())->where('id', $row['source'])->find();
                    if (!empty($order)) {
                        $row['ordername'] = $order['name'];
                        $row['ordermobile'] = $order['mobile'];
                        $row['ordercreated'] = $order['created'];
                    }
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $model = new Agents();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['status', 'in', [1, 2]];
            if (!empty($post['title'])) {
                $where[] = ['accounts|nickname|mobile', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['product'] = (new Product())->where(['agentid' => $lists['id'], 'isdel' => 1])->count();
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, []);
        }
    }

    public function agent_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'nickname' => 'require|chsAlphaNum|length:4,50',
                'accounts' => 'require|alphaNum|length:6,50',
                'mobile' => 'require',
                'lat' => 'require|gt:0',
                'lon' => 'require|gt:0',
            ], [
                'nickname.require' => '备注不能为空',
                'nickname.length' => '备注长度控制在6-20个字符',
                'nickname.chsAlphaNum' => '备注只能是汉字、字母和数字',
                'accounts.require' => '账号不能为空',
                'accounts.alphaNum' => '账号只能是字母和数字',
                'accounts.length' => '账号长度控制在6-50个字符',
                'mobile.require' => '手机不能为空',
                'lat.require' => '坐标不能为空',
                'lat.gt' => '坐标不能为空',
                'lon.require' => '坐标不能为空',
                'lon.gt' => '坐标不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
                $this->result([], 1, '手机格式不正确');
            }
            if (empty($data['id']) && empty($data['password'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家密码必须填写']);
            }
            if (!empty($data['id']) && empty($data['password'])) {
                unset($data['password']);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            }
            $model = new Agents();
            //查找店铺名称、账号是否已经被使用
            $haveshop = $model->where(['accounts' => $data['accounts'], 'status' => [1, 2]])->find();
            if (!empty($data['id'])) {
                if (!empty($haveshop) && $haveshop['id'] != $data['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                if (!empty($haveshop)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                $res = $model->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Agents();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            return view('', [
                'row' => $row
            ]);
        }
    }


    public function agent_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Agents();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update(['status' => 3]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function agent_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new Agents();
            $agent = $model->where(['id' => $id])->find();
            if (empty($agent)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'status':
                    if ($agent['status'] == 3) {
                        return json(['code' => 1, 'data' => [], 'msg' => '账号已被删除']);
                    }
                    $status = $agent['status'] == 1 ? 2 : 1;
                    break;
                case 'openid':
                    $status = null;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function money_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'moneys' => 'require|gt:0',
                'type' => 'require|in:1,2',
                'id' => 'require',
                'types' => 'require|in:1,2',
            ], [
                'id.require' => 'ID不能为空',
                'type.require' => '操作类型不能为空',
                'type.in' => '操作类型不正确',
                'moneys.require' => '金额不能为空',
                'moneys.gt' => '金额必须大于0',
                'types.require' => '钱包种类不能为空',
                'types.in' => '钱包种类不正确',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $data['desc'] = empty($data['desc']) ? '资产变更' : $data['desc'];
            if ($data['type'] == 1) {
                $money = abs($data['moneys']);
            } else {
                $money = -abs($data['moneys']);
            }
            Db::startTrans();
            try {
                if ($data['types'] == 1) {
                    (new Agents())->MoneyEdit($data['id'], 4, $money, $data['desc'], 0);
                } else {
                    (new Agents())->MoneyEdit2($data['id'], 4, $money, $data['desc'], 0);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
    }
}
